use crate::pool;
use rbatis::rbdc::{self, Error};
use rbatis::sql::PageRequest;
use rbatis::{crud, Page, rbdc::db::ExecResult};
use rbatis::{impl_select_page, sql};
use rbdc::datetime::DateTime;
use serde::{Deserialize, Serialize};
use serde_json::Value;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TbLog {
    id: Option<u64>,
    created_at: Option<DateTime>,
    name: String,
    time: DateTime,
    operate: String,
    data: Option<String>,
}

crud!(TbLog {});
impl_select_page!(TbLog {select_page(query: &crate::handlers::log::Get) =>
    "`where 1=1`
    if query.name!=null && query.name!='':
        ` and name=#{query.name}`
    if query.operate!=null && query.operate!='':
        ` and operate like #{'%'+query.operate+'%'}`
    if query.begin_time!=null:
        ` and time>=#{query.begin_time}`
    if query.end_time!=null:
        ` and time<=#{query.end_time}`
    ` order by time desc`" 
});

impl TbLog {
    pub fn new(name: String, operate: &str) -> Self {
        Self {
            id: None,
            created_at: Some(DateTime::now()),
            name,
            time: DateTime::now(),
            operate: operate.to_string(),
            data: None,
        }
    }

    pub fn set_data(mut self, data: Value) -> Self {
        self.data = Some(data.to_string());
        self
    }

    pub async fn insert_log(user: &TbLog) -> Result<ExecResult, Error> {
        TbLog::insert(pool!(), user).await
    }

    pub async fn get_logs(
        page: &crate::common::QueryPage,
        query: &crate::handlers::log::Get,
    ) -> Result<Page<TbLog>, rbdc::Error> {
        TbLog::select_page(pool!(), &PageRequest::from(page), query).await
    }
}
